<template>
  <el-row :gutter="gutter">
    <template v-for="(json, index) in jsonList" :key="index" v-if="modelValue">
      <component :is="componentId" :xs="24" :sm="json.span" :md="json.span" :lg="json.span" :xl="json.span" v-if="!json.options.children">
        <template v-if="$slots[json.options.name]">
          <slot :name="json.options.name"></slot>
        </template>
        <jax-form-item v-model="modelValue[json.options.name]" :options="json.options" v-else></jax-form-item>
      </component>
      <template v-else>
        <jax-form-group v-model="modelValue[json.options.name]" :json="json.options.children"></jax-form-group>
      </template>
    </template>
    <slot></slot>
  </el-row>
</template>

<script>
export default {
  name: 'jax-form-group',
  props: {
    // 表单数据v-model
    modelValue: null,

    // 表单结构
    json: {
      type: Array,
      required: true,
    },

    // 间隔
    gutter: {
      type: Number,
      default: 15,
    },

    // 网格化
    grid: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      jsonList: null,
    }
  },
  computed: {
    componentId() {
      if (this.grid) {
        return 'el-col'
      } else {
        return 'div'
      }
    },
  },
  watch: {
    json() {
      this.jsonList = this.extractToList(this.json)
    },
  },
  created() {
    this.jsonList = this.extractToList(this.json)
  },
  methods: {
    /**
     * 把json中的多维数据提取成一维数据列表，并计算span大小
     */
    extractToList(data, span = 24) {
      let list = []

      data.map((item) => {
        if (Array.isArray(item)) {
          const newList = this.extractToList(item, 24 / item.length)
          list = list.concat(newList)
        } else {
          list.push({
            span: item.span || span,
            options: item,
          })
        }
      })

      return list
    },
  },
}
</script>

<style lang="scss" scoped></style>
